package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Config;
import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DefaultHandler implements Handler {

    @Override
    public void handle(Parameter request, OutputStream response) {
        //TODO：【222024321072046/马云山]
        try {
            //TODO：【222024321072046/马云山]    1. 确认请求URL是根路径 "/"
            String requestUrl = request.getUrl();
            System.out.println("当前请求URL: " + requestUrl); // 调试用：确认是 "/"

            // 2. 根路径映射到 index.html
            String fileName = "/".equals(requestUrl) ? "index.html" : requestUrl.substring(1);
            System.out.println("要读取的文件: " + fileName); // 调试用：确认是 "index.html"

            // 3. 拼接绝对路径（直接用Config中的webRoot，不再依赖相对路径）
            Config config = Config.getInstance();
            Path filePath = Paths.get(config.getWebRoot(), fileName); // 核心：绝对路径拼接

            // 4. 调试用：打印最终路径，确认是否和你的实际路径一致
            String absolutePath = filePath.toAbsolutePath().toString();
            System.out.println("最终文件路径: " + absolutePath);
            System.out.println("文件是否存在: " + Files.exists(filePath));
            System.out.println("是否为目录: " + Files.isDirectory(filePath));

            // 5. 读取文件并返回响应
            if (Files.exists(filePath) && !Files.isDirectory(filePath)) {
                byte[] fileBytes = Files.readAllBytes(filePath);
                // 强制设置HTML类型（避免probeContentType返回null）
                String contentType = "text/html; charset=UTF-8";

                // 构建HTTP响应（必须用\r\n分隔，否则浏览器无法解析）
                String responseHeader = "HTTP/1.1 200 OK\r\n" +
                        "Content-Type: " + contentType + "\r\n" +
                        "Content-Length: " + fileBytes.length + "\r\n" +
                        "Connection: close\r\n" +
                        "\r\n"; // 空行分隔响应头和响应体，必须有！

                // 发送响应
                response.write(responseHeader.getBytes("UTF-8"));
                response.write(fileBytes);
            } else {
                // 404错误：明确提示实际查找的路径，方便排查
                String errorMsg = "<h1>404 Not Found</h1>" +
                        "<p>查找的文件路径：" + absolutePath + "</p>" +
                        "<p>请确认：1. index.html在该路径下 2. 文件名是index.html（小写）</p>";
                String errorHeader = "HTTP/1.1 404 Not Found\r\n" +
                        "Content-Type: text/html; charset=UTF-8\r\n" +
                        "Content-Length: " + errorMsg.getBytes("UTF-8").length + "\r\n" +
                        "Connection: close\r\n" +
                        "\r\n";
                response.write(errorHeader.getBytes("UTF-8"));
                response.write(errorMsg.getBytes("UTF-8"));
            }
        } catch (Exception e) {
            //TODO：【222024321072046/马云山]  500错误：捕获所有异常，打印详细信息
            try {
                String errorMsg = "<h1>500 Internal Server Error</h1>" +
                        "<p>错误原因：" + e.getMessage() + "</p>" +
                        "<p>详细日志请查看控制台</p>";
                String errorHeader = "HTTP/1.1 500 Internal Server Error\r\n" +
                        "Content-Type: text/html; charset=UTF-8\r\n" +
                        "Content-Length: " + errorMsg.getBytes("UTF-8").length + "\r\n" +
                        "Connection: close\r\n" +
                        "\r\n";
                response.write(errorHeader.getBytes("UTF-8"));
                response.write(errorMsg.getBytes("UTF-8"));
                // 控制台打印异常栈，方便定位问题
                System.err.println("处理静态文件时出错：");
                e.printStackTrace();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                response.flush(); // 确保数据全部发送
                response.close(); // 关闭流，释放资源
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}